import yaml
from utils.log_handler import logger


class YamlHandler(object):
    @staticmethod
    def read_data(path, key=None):
        try:
            file = open(path, mode='r', encoding='utf-8')
            data = yaml.load(file, Loader=yaml.SafeLoader)
            file.close()
            if key:
                return data[key]
            return data
        except Exception as e:
            logger.error(f"读取yaml数据失败，失败原因为：{e}，将返回{key}: ''")
            return ""

    @staticmethod
    def write_data(path, data):
        try:
            file = open(path, mode='a', encoding='utf-8')
            yaml.dump(data, stream=file, Dumper=yaml.SafeDumper)
            file.close()
        except Exception as e:
            logger.error(f"写入yaml文件失败，失败原因为：{e}")


yamler = YamlHandler()
